﻿Imports System.Xml
Imports FileNet.Api.Core
Imports System.IO
Imports System.ComponentModel
Imports System.Configuration
Imports IDMObjects

Public Class clsTransferUtility


    Private oCMApi As CMApi.clsUtil
    Private CEConn As CMApi.clsUtil.CEConnection

    Private oIdmViewer As New IDMViewerCtrl.IDMViewerCtrl
    Private m_objNF As IDMObjects.Neighborhood
    Private m_objLibs As IDMObjects.ObjectSet
    Private m_Library As IDMObjects.Library

    Private infoIS2CE As New SortedList
    Private slISDocClass As New SortedList
    Private oDB As clsDBUtility

    Private mLogFolder As String = My.Settings.LogFolder

    Private mSQLIP As String
    Private mSQLUid As String
    Private mSQLPwd As String
    Private mISLibrary As String
    Private mISUid As String
    Private mISPwd As String
    Private mCEIP As String
    Private mCEPort As String
    Private mCEUid As String
    Private mCEPwd As String

    Private mRows As Integer


    'Private mISDocClass As String
    'Private mCEDocClass As String
    'Private mCEObjectStore As String
    'Private mCEFolder As String
    '

    Public Structure IS2CE
        Dim ISClass As String
        Dim CEClass As String
        Dim ObjectStore As String
        Dim Folder As String
        Dim isMerge As String
        Dim idx() As idxInfo
    End Structure
    Public Structure idxInfo
        Dim ISIdx As String
        Dim CEIdx As String
        Dim spec As String
        Dim DoctabaFieldName As String
        Dim DataType As String
    End Structure

    Private mCT As Integer = 0

    Public ReadOnly Property docCt() As Integer
        Get
            Return mCT
        End Get
    End Property


    'Public Sub doTransferByDocClass(ByVal ISDocClass As String, ByVal CEObjectStoreName As String, _
    '                                ByVal CEDocClassName As String, ByVal CEFolder As String)

    '    transfer(True, CEObjectStoreName, ISDocClass, CEDocClassName, CEFolder)
    'End Sub

    ''' <summary>
    ''' 依據 Doc Number 的進行轉檔
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub doTransferByDocNo(ByVal DocNoStart As Integer, _
                                 ByVal DocNoEnd As Integer, _
                                 ByVal DocNoCurr As Integer)
        Dim sSQL As String = String.Empty
        Dim dt As DataTable
        'Dim aryDocNo As String = ReadDocNumber()
        Dim ISDocClass As String = ""
        Try

            If DocNoCurr = 0 Then
                sSQL = "select top " & mRows & " f_docclassnumber,F_docnumber as doc_no,f_entrydate from [FileNetDB].[f_sw].[doctaba] "
                sSQL = sSQL & " where F_docnumber >= " & DocNoStart & " and F_docnumber <= " & Integer.Parse(DocNoEnd)
            Else
                sSQL = "select top " & mRows & " f_docclassnumber,F_docnumber as doc_no,f_entrydate from [FileNetDB].[f_sw].[doctaba] "
                sSQL = sSQL & " where F_docnumber >= " & DocNoCurr + 1 & " and F_docnumber <= " & Integer.Parse(DocNoEnd)

            End If
            System.Console.WriteLine(sSQL)

            dt = oDB.ExecQuery(sSQL)
            Console.WriteLine(dt.Rows.Count)


            If dt.Rows.Count = 0 Then
                WriteDocNumber("9999999999")
            End If
            For Each dr As DataRow In dt.Rows
                Try
                    ISDocClass = slISDocClass(dr("f_docclassnumber"))
                    Console.WriteLine(dr("f_entrydate").ToString)
                    If ISDocClass.ToUpper = "CCheckT".ToUpper Then
                        If dr("f_entrydate") <= 15338 Then
                            Console.WriteLine("Check Entry Date " & dr("f_entrydate").ToString & " <= 15338 (" & DateAdd(DateInterval.Day, 15338, CDate("1970/01/01")).ToString("yyyy/MM/dd") & ") No Need To Trans ")
                            WriteDocNumber(dr("doc_no"))
                            Exit Try
                        End If
                    End If

                    System.Console.WriteLine("transfer" & ISDocClass & "/" & dr("doc_no"))
                    transferbyDocNo(ISDocClass, dr("doc_no"))
                    System.Console.WriteLine("Transfer Finish " & dr("doc_no"))
                    WriteDocNumber(dr("doc_no"))
                Catch ex As Exception
                    System.Console.WriteLine(ex.ToString)
                    writeErrLog(ISDocClass, "", ex.Message)
                End Try
            Next
        Catch ex As Exception
            Console.WriteLine(ex.ToString)

        Finally
            'oIdmViewer = Nothing
        End Try


    End Sub


    Public Sub TransFromTxtFile(ByVal sFileName As String)
        Dim sSQL As String = String.Empty
        Dim dt As DataTable
        'Dim aryDocNo As String = ReadDocNumber()
        Dim ISDocClass As String = ""
        Dim sDocNo As String
        Dim iRead As Integer = 0

        Dim sr As StreamReader = Nothing
        Dim sTxt As String = ""
        If System.IO.File.Exists(sFileName) Then
            sr = System.IO.File.OpenText(sFileName)
            sTxt = sr.ReadLine
            Do Until sTxt Is Nothing
                sDocNo = sTxt.Trim
                sSQL = "select  f_docclassnumber,F_docnumber as doc_no from [FileNetDB].[f_sw].[doctaba] "
                sSQL = sSQL & " where F_docnumber = " & sDocNo
                System.Console.WriteLine(sSQL)
                dt = oDB.ExecQuery(sSQL)
                For Each dr As DataRow In dt.Rows
                    Try
                        ISDocClass = slISDocClass(dr("f_docclassnumber"))
                        System.Console.WriteLine("transfer" & ISDocClass & "/" & dr("doc_no"))
                        transferbyDocNo(ISDocClass, dr("doc_no"))
                        System.Console.WriteLine("Transfer Finish " & dr("doc_no"))
                        WriteDocNumber(dr("doc_no"))
                    Catch ex As Exception
                        System.Console.WriteLine(ex.ToString)
                        writeErrLog(ISDocClass, "", ex.Message)
                    End Try
                Next
                sTxt = sr.ReadLine
            Loop
        Else
            System.Console.WriteLine("file not exist ; press any key to exit ")
            System.Console.ReadKey()
        End If

        m_Library.Logoff()
        oCMApi.LogoffCE(True)



    End Sub


    Private Sub ConnSQL(ByVal SQLIP As String, ByVal SQLUid As String, ByVal SQLPwd As String)
        Dim sSQL As String
        Dim dt As DataTable
        Try
            sSQL = "select getdate()"
            dt = oDB.ExecQuery(sSQL)
            setIS2CE("IStoCE.xml")
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try
    End Sub


    Private Sub ConnCE(ByVal CEIP As String, ByVal CEPort As String, _
                       ByVal CEUserId As String, ByVal CEPwd As String)
        Dim ceURI As String = "http://" & CEIP & ":" & CEPort & "/wsi/FNCEWS40MTOM/"
        Try
            System.Console.WriteLine(ceURI & " / " & CEUserId & " / " & CEPwd)
            oCMApi = New CMApi.clsUtil(mLogFolder, "trace")
            CEConn = oCMApi.LogonCE(CEUserId, CEPwd, ceURI)
        Catch ex As Exception
            Throw New Exception("Logon CE Fail " & ex.Message)
        End Try
    End Sub


    Private Sub ConnIS(ByVal ISLibraryName As String, ByVal ISUserID As String, ByVal ISPwd As String)
        Dim blnReturn As Boolean
        m_objNF = New IDMObjects.Neighborhood
        m_objLibs = m_objNF.Libraries
        For i As Integer = 1 To m_objLibs.Count
            m_Library = m_objLibs(i)
            If (m_Library.Name = ISLibraryName) Then
                If m_Library.GetState(IDMObjects.idmLibraryState.idmLibraryLoggedOn) = False Then
                    Console.WriteLine("Logon IS")
                    blnReturn = m_Library.Logon(ISUserID, ISPwd, , IDMObjects.idmLibraryLogon.idmLogonOptNoUI)
                    If (blnReturn = False) Then
                        Throw New Exception("FileNET登入失敗")
                    Else

                    End If
                End If
                Me.GenISDocClass()
                'FOR TEST
                'Dim slDocPath As New SortedList
                'GetISImage("CComsumerLoanT", False, Integer.Parse("51254879"), slDocPath)
                'Console.ReadKey()
                Exit For
            End If
        Next
    End Sub

    ''' <summary>
    ''' 載入 FileNet IS 的 DocClass
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub GenISDocClass()
        Dim sSQL As String
        Dim dt As DataTable
        Try
            slISDocClass.Clear()
            sSQL = "select f_docclassnumber,f_docclassname from [FileNetDB].[f_sw].[document_class] "
            dt = oDB.ExecQuery(sSQL)
            For Each dr As DataRow In dt.Rows
                System.Console.WriteLine(dr("f_docclassnumber") & "/ " & dr("f_docclassname"))
                slISDocClass.Add(dr("f_docclassnumber"), dr("f_docclassname"))
            Next

        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try
    End Sub

    '''' <summary>
    '''' 
    '''' </summary>
    '''' <param name="isMerge">是否須合併</param>
    '''' <param name="CEObjectStore">Object Store</param>
    '''' <param name="ISDocClass">IS Doc Class</param>
    '''' <param name="CEDocClass">CE Doc Class</param>
    '''' <param name="CEFolder">CE Filing Folder</param>
    '''' <remarks></remarks>
    'Private Sub transfer(ByVal isMerge As Boolean, ByVal CEObjectStore As String, _
    '                     ByVal ISDocClass As String, ByVal CEDocClass As String, ByVal CEFolder As String)
    '    Dim sSQL As String
    '    Dim dt As DataTable
    '    '將CE的Property取出
    '    Dim ClassInfo As clsTransferUtility.IS2CE = infoIS2CE.GetByIndex(infoIS2CE.IndexOfKey(ISDocClass))
    '    Dim props() As CMApi.clsUtil.PropertyInfo = Nothing
    '    Dim slDoc As New ArrayList
    '    Dim oDoc As IDocument
    '    Dim sDocid As String = ""
    '    '先組成取出IS Doctaba 資料的 SQL
    '    Try

    '        sSQL = GenGETISSQL(ISDocClass)
    '        dt = oDB.ExecQuery(sSQL)
    '        For Each dr As DataRow In dt.Rows
    '            Dim slDocPath As New SortedList
    '            sDocid = dr("doc_no")
    '            GetISImage(ISDocClass, isMerge, dr("doc_no"), slDocPath)


    '            For iCacheFileCT As Integer = 0 To slDocPath.Count - 1
    '                Try
    '                    ReDim props(ClassInfo.idx.GetUpperBound(0))

    '                    For iProp As Integer = ClassInfo.idx.GetLowerBound(0) To ClassInfo.idx.GetUpperBound(0)
    '                        With props(iProp)
    '                            If dt.Columns.Contains(ClassInfo.idx(iProp).ISIdx) Then
    '                                .PropertyName = ClassInfo.idx(iProp).CEIdx
    '                                If IsDBNull(dr(ClassInfo.idx(iProp).ISIdx)) Then
    '                                    Select Case ClassInfo.idx(iProp).DataType
    '                                        Case "N"
    '                                            .PropertyValue = 1
    '                                        Case "C"
    '                                            .PropertyValue = ""
    '                                    End Select

    '                                Else
    '                                    Select Case ClassInfo.idx(iProp).DataType
    '                                        Case "N"
    '                                            If IsNumeric(dr(ClassInfo.idx(iProp).ISIdx)) Then
    '                                                .PropertyValue = Integer.Parse(dr(ClassInfo.idx(iProp).ISIdx))
    '                                            Else
    '                                                .PropertyValue = 1
    '                                            End If

    '                                        Case "C"
    '                                            .PropertyValue = dr(ClassInfo.idx(iProp).ISIdx).ToString
    '                                    End Select

    '                                End If
    '                                If ClassInfo.idx(iProp).CEIdx.ToLower = "FnDocNumber".ToLower Then
    '                                    .PropertyValue = CInt(dr(ClassInfo.idx(iProp).ISIdx))
    '                                End If
    '                            Else
    '                                If ClassInfo.idx(iProp).CEIdx.ToLower = "PageNo".ToLower Then
    '                                    .PropertyName = "PageNo"
    '                                    .PropertyValue = iCacheFileCT + 1
    '                                End If
    '                                If ClassInfo.idx(iProp).CEIdx.ToLower = "DocPages".ToLower Then
    '                                    .PropertyName = "DocPages"
    '                                    .PropertyValue = 1
    '                                End If
    '                            End If
    '                        End With
    '                    Next
    '                    Dim cacheFile As String = slDocPath.GetByIndex(iCacheFileCT)
    '                    Dim oFileInfo As New System.IO.FileInfo(cacheFile)
    '                    '票據的附檔名為 jpg
    '                    If ISDocClass.ToLower = "CCheckT".ToLower Then
    '                        cacheFile = System.IO.Path.ChangeExtension(cacheFile, "jpg")
    '                    Else
    '                        cacheFile = System.IO.Path.ChangeExtension(cacheFile, "tif")
    '                    End If
    '                    If File.Exists(cacheFile) Then
    '                        'do nothing
    '                    Else
    '                        oFileInfo.MoveTo(cacheFile)
    '                    End If
    '                    oDoc = oCMApi.CreateDoc(CEObjectStore, CEDocClass, cacheFile, _
    '                                            True, ConvertExtFileNameToMIME(cacheFile), _
    '                                            "TITLE", True, CEFolder, props, True, _
    '                                            FileNet.Api.Constants.CheckinType.MAJOR_VERSION)
    '                    slDoc.Add(oDoc)
    '                Catch ex As Exception
    '                    writeErrLog(ISDocClass, sDocid, ex.Message)
    '                    writeErrLog(ISDocClass, sDocid, "Delete Doc ")
    '                    For iDocCT As Integer = 0 To slDoc.Count - 1
    '                        oCMApi.DeleteDoc(slDoc(iDocCT))
    '                    Next
    '                End Try

    '            Next
    '        Next
    '    Catch ex As Exception
    '        writeErrLog(ISDocClass, sDocid, ex.Message)
    '    End Try
    'End Sub



    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="ISDocClass">IS Doc Class</param>
    ''' <remarks></remarks>
    Private Sub transferbyDocNo(ByVal ISDocClass As String, ByVal docNo As String)
        Dim sSQL As String
        Dim dt As DataTable
        '將CE的Property取出
        Dim ClassInfo As clsTransferUtility.IS2CE
        Dim props() As CMApi.clsUtil.PropertyInfo = Nothing
        Dim slIDocument As New ArrayList
        Dim oIDocument As IDocument
        Dim sDocid As String = ""
        Dim oLog As New LogHandler.clsLogger
        '先組成取出IS Doctaba 資料的 SQL
        Try
            System.Console.WriteLine(ISDocClass)
            ClassInfo = infoIS2CE.GetByIndex(infoIS2CE.IndexOfKey(ISDocClass))
            sSQL = GenGETISSQL(ISDocClass, docNo)
            System.Console.WriteLine(sSQL)
            dt = oDB.ExecQuery(sSQL)
            For Each dr As DataRow In dt.Rows
                Dim slDocPath As New SortedList
                sDocid = docNo
                GetISImage(ISDocClass, IIf(ClassInfo.isMerge.ToUpper = "Y", True, False), Integer.Parse(docNo), slDocPath)

                For iCacheFileCT As Integer = 0 To slDocPath.Count - 1
                    Try
                        ReDim props(ClassInfo.idx.GetUpperBound(0))

                        For iProp As Integer = ClassInfo.idx.GetLowerBound(0) To ClassInfo.idx.GetUpperBound(0)

                            'With props(iProp)
                            '    If dt.Columns.Contains(ClassInfo.idx(iProp).ISIdx) Then
                            '        .PropertyName = ClassInfo.idx(iProp).CEIdx
                            '        If IsDBNull(dr(ClassInfo.idx(iProp).ISIdx)) Then
                            '            .PropertyValue = ""
                            '        Else
                            '            .PropertyValue = dr(ClassInfo.idx(iProp).ISIdx)
                            '        End If
                            '        If ClassInfo.idx(iProp).CEIdx.ToLower = "FnDocNumber".ToLower Then
                            '            .PropertyValue = CInt(dr(ClassInfo.idx(iProp).ISIdx))
                            '        End If
                            '    Else
                            '        If ClassInfo.idx(iProp).CEIdx.ToLower = "PageNo".ToLower Then
                            '            .PropertyName = "PageNo"
                            '            .PropertyValue = iCacheFileCT + 1
                            '        End If
                            '        If ClassInfo.idx(iProp).CEIdx.ToLower = "DocPages".ToLower Then
                            '            .PropertyName = "DocPages"
                            '            .PropertyValue = 1
                            '        End If
                            '    End If
                            'End With

                            With props(iProp)
                                If dt.Columns.Contains(ClassInfo.idx(iProp).ISIdx) Then
                                    .PropertyName = ClassInfo.idx(iProp).CEIdx
                                    If IsDBNull(dr(ClassInfo.idx(iProp).ISIdx)) Then
                                        Select Case ClassInfo.idx(iProp).DataType
                                            Case "N"
                                                .PropertyValue = 1
                                            Case "C"
                                                .PropertyValue = ""
                                        End Select

                                    Else
                                        Select Case ClassInfo.idx(iProp).DataType
                                            Case "N"
                                                If IsNumeric(dr(ClassInfo.idx(iProp).ISIdx)) Then
                                                    .PropertyValue = Integer.Parse(dr(ClassInfo.idx(iProp).ISIdx))
                                                Else
                                                    .PropertyValue = 1
                                                End If

                                            Case "C"
                                                .PropertyValue = dr(ClassInfo.idx(iProp).ISIdx).ToString
                                        End Select

                                    End If
                                    If ClassInfo.idx(iProp).CEIdx.ToLower = "FnDocNumber".ToLower Then
                                        .PropertyValue = CInt(dr(ClassInfo.idx(iProp).ISIdx))
                                    End If
                                    If ClassInfo.idx(iProp).CEIdx.ToLower = "CEFnDocNumber".ToLower Then
                                        .PropertyValue = CInt(dr(ClassInfo.idx(iProp).ISIdx)).ToString.PadLeft(9, "0")
                                    End If

                                Else
                                    If ClassInfo.idx(iProp).CEIdx.ToLower = "PageNo".ToLower Then
                                        .PropertyName = "PageNo"
                                        .PropertyValue = iCacheFileCT + 1
                                    End If
                                    If ClassInfo.idx(iProp).CEIdx.ToLower = "DocPages".ToLower Then
                                        .PropertyName = "DocPages"
                                        .PropertyValue = 1
                                    End If
                                End If
                            End With
                        Next
                        Dim cacheFile As String = slDocPath.GetByIndex(iCacheFileCT)
                        Dim oFileInfo As New System.IO.FileInfo(cacheFile)
                        '票據的附檔名為 jpg
                        If ISDocClass.ToLower = "CCheckT".ToLower Then
                            cacheFile = System.IO.Path.ChangeExtension(cacheFile, "jpg")
                            slDocPath.SetByIndex(iCacheFileCT, cacheFile)
                        Else
                            cacheFile = System.IO.Path.ChangeExtension(cacheFile, "tif")
                        End If
                        If File.Exists(cacheFile) Then
                            'do nothing
                        Else
                            oFileInfo.MoveTo(cacheFile)
                        End If
                        System.Console.WriteLine("create ce doc")
                        Dim sfolder As String = TransFolder(ClassInfo.Folder, dr("ApplNo"))
                        Dim docTitle As String = ""
                        If ClassInfo.CEClass = "CConsumerLoanT" Then
                            docTitle = dr("ApplNo") & "_" & dr("FormId") & "_" & dr("f_entrydate")
                        ElseIf ClassInfo.CEClass = "CConsumerLoanF" Then
                            docTitle = dr("FormId") & "_" & dr("f_entrydate")
                        ElseIf ClassInfo.CEClass = "CCheckT" Then
                            docTitle = dr("ApplNo")
                        End If
                        Console.WriteLine("Do Create CMApi.CreadeDoc")
                        Console.WriteLine(ClassInfo.ObjectStore)
                        Console.WriteLine(ClassInfo.CEClass)
                        'Console.WriteLine(ConvertExtFileNameToMIME(cacheFile))
                        Console.WriteLine(sfolder)
                        Console.WriteLine(cacheFile)
                        For ipro As Integer = props.GetLowerBound(0) To props.GetUpperBound(0)
                            Console.WriteLine(props(ipro).PropertyName & " " & props(ipro).PropertyValue)
                        Next
                        'ConnCE(My.Settings.CEIP, My.Settings.CEPort, My.Settings.CEUid, My.Settings.CEPwd)
                        oIDocument = oCMApi.CreateDoc(ClassInfo.ObjectStore, ClassInfo.CEClass, cacheFile, _
                                                True, ConvertExtFileNameToMIME(cacheFile), _
                                                docTitle, True, sfolder, props, True, _
                                                FileNet.Api.Constants.CheckinType.MAJOR_VERSION)
                        Console.WriteLine("End Do Create CMApi.CreadeDoc")
                        slIDocument.Add(oIDocument)
                    Catch ex As Exception
                        Console.WriteLine("error")
                        Console.ReadKey()
                        System.Console.WriteLine(ex.ToString)
                        writeErrLog(ISDocClass, sDocid, ex.Message)
                        writeErrLog(ISDocClass, sDocid, "Delete Doc ")
                        WriteBadData(sDocid)
                        For iDocCT As Integer = 0 To slIDocument.Count - 1
                            oCMApi.DeleteDoc(slIDocument(iDocCT))
                        Next
                        GoTo NextDoc
                    End Try

                Next
                '處理成功筆數+1
                mCT = mCT + 1
                writeLog(ISDocClass, sDocid, slIDocument)
                Dim sFileInfo As String = ""
                For ii As Integer = 0 To slDocPath.Count - 1
                    Dim oFileInfo As New FileInfo(slDocPath.GetByIndex(ii))
                    With oFileInfo
                        sFileInfo = .FullName & "|" & .Name & "|" & (.Length / 1024).ToString
                    End With
                    oLog.writeLine(My.Settings.LogFolder, "FileSize", sFileInfo)
                    Console.WriteLine(slDocPath.GetByIndex(ii))
                    System.IO.File.SetAttributes(slDocPath.GetByIndex(ii), FileAttributes.Normal)
                    System.IO.File.Delete(slDocPath.GetByIndex(ii))

                Next
NextDoc:
                '轉檔完畢,刪除 Doc

            Next
        Catch ex As Exception
            System.Console.WriteLine(ex.ToString)
            writeErrLog(ISDocClass, sDocid, ex.Message)
        End Try
    End Sub

    ''' <summary>
    ''' 解析 IS to CE 的 XML 定義檔
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub setIS2CE(ByVal xmlFilePath As String)
        Dim xmlDoc As New XmlDocument
        Dim xmlNodeList As XmlNodeList
        Dim xmlNode As XmlNode = Nothing
        Dim tmp() As clsTransferUtility.idxInfo = Nothing
        Dim ClassInfo As clsTransferUtility.IS2CE = Nothing

        Try
            infoIS2CE.Clear()
            xmlDoc.Load(xmlFilePath)
            xmlNodeList = xmlDoc.GetElementsByTagName("DocClass")
            For i As Integer = 0 To xmlNodeList.Count - 1
                xmlNode = xmlNodeList.Item(i)
                ReDim tmp(xmlNode.ChildNodes.Count - 1)
                With ClassInfo
                    .ISClass = xmlNode.Attributes("IS").Value
                    .CEClass = xmlNode.Attributes("CE").Value
                    .ObjectStore = xmlNode.Attributes("ObjectStore").Value
                    .Folder = xmlNode.Attributes("Folder").Value
                    .isMerge = xmlNode.Attributes("isMerge").Value
                    For j As Integer = tmp.GetLowerBound(0) To tmp.GetUpperBound(0)
                        With tmp(j)
                            .ISIdx = xmlNode.ChildNodes(j).Attributes("IS").Value
                            .CEIdx = xmlNode.ChildNodes(j).Attributes("CE").Value
                            .spec = xmlNode.ChildNodes(j).Attributes("SPEC").Value
                            .DataType = xmlNode.ChildNodes(j).Attributes("DataType").Value
                            .DoctabaFieldName = GetDoctabaField(.ISIdx)
                        End With
                    Next
                    .idx = tmp
                    infoIS2CE.Add(xmlNode.Attributes("IS").Value, ClassInfo)
                End With
            Next


        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try


    End Sub

    ''' <summary>
    ''' 傳入 index名稱,判斷是否存在於 FileNet IS 定義中,若不是不須組成SQL 中的欄位
    ''' </summary>
    ''' <param name="idxName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetDoctabaField(ByVal idxName As String) As String
        Dim sSQL As String = ""
        Dim dt As DataTable
        Try
            sSQL = " SELECT f_columnname,f_indexname from [FileNetDB].[f_sw].[user_index] where f_indexname='" & idxName & "'"
            dt = oDB.ExecQuery(sSQL)
            If dt.Rows.Count > 0 Then
                Return IIf(IsDBNull(dt.Rows(0)("f_columnname")), idxName, dt.Rows(0)("f_columnname"))
            Else
                Return ""
            End If
        Catch ex As Exception
            writeErrLog("", "", sSQL)
            writeErrLog("", "", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try

    End Function

    ''' <summary>
    ''' 依據附檔名轉出MIME Type
    ''' </summary>
    ''' <param name="sFileName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ConvertExtFileNameToMIME(ByVal sFileName As String) As CMApi.clsUtil.MimeType
        Dim sMime As String
        Dim aryMime() As String
        Dim sExtName As String
        Dim oMime As CMApi.clsUtil.MimeType
        sExtName = System.IO.Path.GetExtension(sFileName)
        aryMime = [Enum].GetNames(GetType(CMApi.clsUtil.MimeType))
        For i As Integer = aryMime.GetLowerBound(0) To aryMime.GetUpperBound(0)
            sMime = aryMime(i)
            Dim oMimeInfo As Reflection.FieldInfo = GetType(CMApi.clsUtil.MimeType).GetField(sMime)
            Dim attr As DescriptionAttribute = DirectCast(oMimeInfo.GetCustomAttributes(GetType(DescriptionAttribute), False)(0), DescriptionAttribute)
            If attr.Description.Split(";")(1) = sExtName Then
                oMime = [Enum].Parse(GetType(CMApi.clsUtil.MimeType), sMime)
                Exit For
            End If
        Next
        'Console.WriteLine(sMime)
        Return oMime
    End Function


    ''' <summary>
    ''' 組成查詢 IS Document Number 的 SQL Script
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GenGETISSQL(ByVal ISDocClass As String, Optional ByVal DocNo As String = "")
        Dim docclassnumber As Integer
        Dim ClassInfo As clsTransferUtility.IS2CE = Nothing
        Dim sSQL As String = "select "
        docclassnumber = slISDocClass.GetKey(slISDocClass.IndexOfValue(ISDocClass))
        ClassInfo = infoIS2CE.GetByIndex(infoIS2CE.IndexOfKey(ISDocClass))
        With ClassInfo
            For i As Integer = .idx.GetLowerBound(0) To .idx.GetUpperBound(0)

                Select Case .idx(i).spec

                    Case "F_Docclassname"
                        sSQL = sSQL & "'" & ISDocClass & "' as " & .idx(i).ISIdx & " , "

                    Case "N"
                        sSQL = sSQL & IIf(.idx(i).DoctabaFieldName = "", "'" & "'", .idx(i).DoctabaFieldName) & " as " & .idx(i).ISIdx & " , "
                    Case "EntryDate"
                        sSQL = sSQL & "convert(varchar(8),dateadd(D," & .idx(i).DoctabaFieldName & ",'1970/01/01'),112) as " & .idx(i).ISIdx & " , "
                End Select

            Next
        End With
        sSQL = sSQL & " f_docclassnumber,F_docnumber as doc_no from [FileNetDB].[f_sw].[doctaba]  where f_docclassnumber = " & docclassnumber
        If DocNo = "" Then
            sSQL = sSQL & " order by F_docnumber "
        Else
            sSQL = sSQL & " and f_docnumber = " & DocNo & " order by F_docnumber "
        End If
        'If txtDocNoStart.Text <> "" AndAlso txtDocNoEnd.Text <> "" Then
        '    sSQL = sSQL & " and F_docnumber  >= " & txtDocNoStart.Text & " and F_docnumber <= " & txtDocNoEnd.Text
        'End If
        Return sSQL
    End Function



    ''' <summary>
    ''' 記錄 IS Doc Id 對應到 CE 的 Doc Id
    ''' </summary>
    ''' <param name="ISDocId"></param>
    ''' <remarks></remarks>
    Private Sub writeLog(ByVal ISDocClass As String, ByVal ISDocId As String, ByVal CEDocId As ArrayList)
        '轉檔記錄的檔名為 IM2CM_ISDocClassName.txt
        Dim logFileName As String = mLogFolder.Trim("\") & "\" & "IM2CM_" & ISDocClass & "_" & Now.ToString("dd") & ".txt"
        Dim oStreamWriter As StreamWriter
        Dim oFileStream As FileStream
        If Directory.Exists(mLogFolder) = False Then
            Directory.CreateDirectory(mLogFolder)
        End If
        If File.Exists(logFileName) = False Then
            oFileStream = File.Create(logFileName)
            oFileStream.Close()
        End If
        oStreamWriter = New StreamWriter(logFileName, True, System.Text.Encoding.Default)
        For i As Integer = 0 To CEDocId.Count - 1
            Dim sCEDocid As String
            sCEDocid = CType(CEDocId.Item(i), IDocument).Id.ToString
            oStreamWriter.WriteLine(Now.ToString("yyyy/MM/dd HH:mm:ss.fff") & "   IS Doc id : " & ISDocId & " ; CE Doc id : " & sCEDocid)
        Next
        oStreamWriter.Flush()
        oStreamWriter.Close()

    End Sub


    ''' <summary>
    ''' 記錄錯誤訊息
    ''' </summary>
    ''' <param name="ISDocId"></param>
    ''' <param name="errTxt"></param>
    ''' <remarks></remarks>
    Private Sub writeErrLog(ByVal ISDocClass As String, ByVal ISDocId As String, ByVal errTxt As String)
        '轉檔記錄的檔名為 IM2CM_ISDocClassName.txt
        Dim logFileName As String = mLogFolder.Trim("\") & "\" & "IM2CM_" & ISDocClass & "_Error" & "_" & Now.ToString("dd") & ".txt"
        Dim oStreamWriter As StreamWriter
        Dim oFileStream As FileStream
        If Directory.Exists(mLogFolder) = False Then
            Directory.CreateDirectory(mLogFolder)
        End If
        If File.Exists(logFileName) = False Then
            oFileStream = File.Create(logFileName)
            oFileStream.Close()
        End If
        oStreamWriter = New StreamWriter(logFileName, True, System.Text.Encoding.Default)
        oStreamWriter.WriteLine("IS Doc id : " & ISDocId)
        oStreamWriter.WriteLine("Error : " & errTxt)

        oStreamWriter.Flush()
        oStreamWriter.Close()
        'WriteBadData(ISDocId)
    End Sub


    Private Sub WriteBadData(ByVal sDocId As String)
        Dim logFileName As String = mLogFolder.Trim("\") & "\" & "IM2CM_" & Now.ToString("yyyyMMdd") & "_bad.txt"
        Dim oStreamWriter As StreamWriter
        Dim oFileStream As FileStream
        If Directory.Exists(mLogFolder) = False Then
            Directory.CreateDirectory(mLogFolder)
        End If
        If File.Exists(logFileName) = False Then
            oFileStream = File.Create(logFileName)
            oFileStream.Close()
        End If
        oStreamWriter = New StreamWriter(logFileName, True, System.Text.Encoding.Default)
        oStreamWriter.WriteLine(sDocId)

        oStreamWriter.Flush()
        oStreamWriter.Close()
    End Sub

    ''' <summary>
    ''' 傳入 Doc No 取出對應的檔案
    ''' </summary>
    ''' <param name="docnum"></param>
    ''' <remarks></remarks>
    Private Sub GetISImage(ByVal sDocClass As String, ByVal isMerge As Boolean, ByVal docnum As Integer, ByRef slFilePath As SortedList)
        Dim oISDoc As IDMObjects.Document
        Dim slISDoc As New SortedList
        Dim oMerge As New Object
        Dim aryFiles As New ArrayList
        Try
            System.Console.WriteLine("Get Image " & docnum)
            oISDoc = m_Library.GetObject(IDMObjects.idmObjectType.idmObjTypeDocument, docnum)

            If isMerge = True Then
                System.Console.WriteLine("Merge Image ")
                For iPageNo As Integer = 1 To oISDoc.PageCount
                    Dim tmpFileName As String
                    tmpFileName = oISDoc.GetCachedFile(iPageNo)
                    Dim oFileInfo As New System.IO.FileInfo(tmpFileName)
                    tmpFileName = System.IO.Path.ChangeExtension(tmpFileName, "tif")
                    If File.Exists(tmpFileName) Then
                        'do nothing
                    Else
                        oFileInfo.MoveTo(tmpFileName)
                    End If

                    aryFiles.Add(tmpFileName)

                Next
                If System.IO.Directory.Exists(mLogFolder.Trim("\") & "\ISFile\") = False Then
                    System.IO.Directory.CreateDirectory(mLogFolder.Trim("\") & "\ISFile\")
                End If
                oMerge.JoinTiffImages(aryFiles, mLogFolder.Trim("\") & "\ISFile\" & "IS_" & docnum.ToString & ".tif", Imaging.EncoderValue.CompressionCCITT4)
                slISDoc.Add(1, mLogFolder.Trim("\") & "\ISFile\" & "IS_" & docnum.ToString & ".tif")
            Else
                For iPageNo As Integer = 1 To oISDoc.PageCount
                    Console.WriteLine(oISDoc.GetCachedFile(iPageNo))
                    slISDoc.Add(iPageNo, oISDoc.GetCachedFile(iPageNo))
                Next
            End If

            slFilePath = slISDoc
        Catch ex As Exception
            System.Console.WriteLine(ex.ToString)
            writeErrLog(sDocClass, docnum, ex.Message)
        End Try

    End Sub

    ''' <summary>
    ''' 初始化參數
    ''' </summary>
    ''' <param name="sLogFolder"></param>
    ''' <remarks></remarks>
    Public Sub init(ByVal sLogFolder As String)

        Try


            With My.Settings
                mSQLIP = .FileNetDB_IP
                mSQLUid = .FileNetDB_Uid 'System.Configuration.ConfigurationManager.AppSettings("FileNetDB_Uid")
                mSQLPwd = .FileNetDB_PWD 'System.Configuration.ConfigurationManager.AppSettings("FileNetDB_PWD")

                mCEIP = .CEIP 'System.Configuration.ConfigurationManager.AppSettings("CEIP")
                mCEPort = .CEPort 'System.Configuration.ConfigurationManager.AppSettings("CEPort")
                mCEUid = .CEUid 'System.Configuration.ConfigurationManager.AppSettings("CEUid")
                mCEPwd = .CEPwd 'System.Configuration.ConfigurationManager.AppSettings("CEPwd")

                mISLibrary = .ISLibrary 'System.Configuration.ConfigurationManager.AppSettings("ISLibrary")
                mISUid = .ISUid 'System.Configuration.ConfigurationManager.AppSettings("ISUid")
                mISPwd = .ISPwd 'System.Configuration.ConfigurationManager.AppSettings("ISPwd")

                mRows = .rows 'System.Configuration.ConfigurationManager.AppSettings("rows")

                mLogFolder = .LogFolder
            End With

            System.Console.WriteLine("Conn to SQL Server " & mSQLIP & " / " & mSQLUid & " / " & mSQLPwd)
            oDB = New clsDBUtility(mSQLIP, mSQLUid, mSQLPwd)
            Try
                Dim dt As DataTable = oDB.ExecQuery("select getdate()")

            Catch ex As Exception
                System.Console.WriteLine(" Conn SQL Server Fail ")
                Throw New Exception(" Conn SQL Server Fail")
            End Try

            Try
                System.Console.WriteLine("Conn to ce Server " & mCEIP & ":" & mCEPort & " / " & mCEUid & " / " & mCEPwd)
                ConnCE(mCEIP, mCEPort, mCEUid, mCEPwd)
                setIS2CE(My.Settings.xmlFolder)
            Catch ex As Exception
                System.Console.WriteLine(" Conn CE Server Fail ")
                Throw New Exception(" Conn CE Server Fail")
            End Try

            Try
                System.Console.WriteLine("Conn to IS Server " & mISLibrary & " / " & mISUid & " / " & mISPwd)
                ConnIS(mISLibrary, mISUid, mISPwd)
            Catch ex As Exception
                System.Console.WriteLine(" Conn IS Server Fail ")
                Throw New Exception(" Conn IS Server Fail")
            End Try

        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 紀錄已處理完成的 Doc Number
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub WriteDocNumber(ByVal CurrDocNo As Integer)
        'Dim logFileName As String = mLogFolder.Trim("\") & "\" & "IM2CM_DocNo" & sDocClass & ".txt"
        'Dim oStreamWriter As StreamWriter
        'Dim oFileStream As FileStream
        'If Directory.Exists(mLogFolder) = False Then
        '    Directory.CreateDirectory(mLogFolder)
        'End If
        'If File.Exists(logFileName) = False Then
        '    oFileStream = File.Create(logFileName)
        '    oFileStream.Close()
        'End If
        'oStreamWriter = New StreamWriter(logFileName, False, System.Text.Encoding.Default)
        'oStreamWriter.WriteLine("DocNo : " & CurrDocNo)
        'oStreamWriter.Flush()
        'oStreamWriter.Close()
        System.Console.WriteLine("Write Log " & CurrDocNo)
        My.Settings.CurrDoc = CurrDocNo
        My.Settings.Save()
    End Sub

    ''' <summary>
    ''' 讀取文字檔中紀錄的 Doc No
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ReadDocNumber() As String
        'Dim MainFile As String = mLogFolder.Trim("\") & "\" & "IM2CM_DocNo" & sDocClass & ".txt"
        'Dim oRead As System.IO.StreamReader
        'Dim sTxt As String = ""
        'If System.IO.File.Exists(MainFile) = False Then
        '    Return "0"
        'End If
        'My.Settings.Item("DocStart") = "800"
        'My.Settings.Save()
        'oRead = New IO.StreamReader(MainFile, System.Text.Encoding.Default)
        'oRead = IO.File.OpenText(MainFile)
        'sTxt = oRead.ReadLine()
        'If sTxt.IndexOf(":") < 0 Then
        '    Return "0"
        'Else
        '    Return sTxt.Split(":")(1).Trim
        'End If
        Return My.Settings.CurrDoc
    End Function

    Private Function TransFolder(ByVal BaseFolder As String, ByVal ApplNo As String)
        Console.WriteLine(ApplNo)
        Try
            Select Case BaseFolder
                Case "/CLFolder"
                    If ApplNo.Substring(0, 2) = "CC" Then
                        Return BaseFolder & "/" & Integer.Parse(ApplNo.Substring(4, 3)) + 1911
                    Else
                        Return BaseFolder & "/OldCase"
                    End If
                Case "/CLFolderF"
                    Return BaseFolder
                Case "/CKFolder"
                    Return "/" & BaseFolder & "/" & ApplNo.Substring(0, 6)
                Case Else
                    Return "/"
            End Select
        Catch ex As Exception
            Return "/"
        Finally

        End Try

    End Function
End Class
